package com.changwu.cwbase.temples;

import android.app.Activity;
import android.content.Context;
import android.webkit.JavascriptInterface;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.changwu.cwbase.Constants;
import com.changwu.cwbase.Controllers;
import com.changwu.cwbase.bean.entity.User;
import com.changwu.cwbase.bean.model.UserModel;
import com.changwu.cwbase.event.LogoutEvent;
import com.changwu.cwbase.ui.commont.CommonWebActivity;
import com.changwu.cwbase.ui.activity.main.MainActivity;
import com.changwu.cwbase.util.IntentUtil;
import com.changwu.cwbase.util.PreferencesUtil;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;


/**
 * Created by cenxiaozhong on 2017/5/14.
 * source code  https://github.com/Justson/AgentWeb
 */

public class AndroidInterface {
    private Context context;
    private Activity activity;

    public AndroidInterface(Context context) {
        this.context = context;
        this.activity = (Activity) context;
    }


    @JavascriptInterface
    public void callAndroid(final String msg) {

        ToastUtils.showShort(msg);

    }

    @JavascriptInterface
    public void logout() {
        EventBus.getDefault().post(new LogoutEvent());
    }

    @JavascriptInterface
    public void goActivity(String title, String url) {
        IntentUtil.startActivity((Activity) context, CommonWebActivity.class, 0, Constants.TITLE, title, Constants.URL, Controllers.webPrefix + url);
    }

    @JavascriptInterface
    public void loginSuccess(String data) {
        User user = new Gson().fromJson(data, User.class);
        PreferencesUtil.saveStringData(Constants.USER, JSON.toJSONString(user));
        UserModel.getInstance().initUserInfo();
    }

    @JavascriptInterface
    public void goMain() {
        IntentUtil.startActivity(activity, MainActivity.class);
        activity.finish();
    }


}
